//
//  ComposeViewController.m
//  SinaWeiboOAuthDemo
//
//  Created by junmin liu on 11-1-4.
//  Copyright 2011 Openlab. All rights reserved.
//

#import "ComposeViewController.h"
#import "ConstantStrings.h"


#define SEND_SEGMENT_CNTRL_WIDTH			130
#define FIRST_SEND_SEGMENT_WIDTH			 66

#define IMAGES_SEGMENT_CONTROLLER_TAG		487
#define SEND_TWIT_SEGMENT_CONTROLLER_TAG	 42

#define PROGRESS_ACTION_SHEET_TAG										214
#define PHOTO_Q_SHEET_TAG												436
#define PROCESSING_PHOTO_SHEET_TAG										3

#define PHOTO_ENABLE_SERVICES_ALERT_TAG									666
#define PHOTO_DO_CANCEL_ALERT_TAG										13

#define K_UI_TYPE_MOVIE													@"public.movie"
#define K_UI_TYPE_IMAGE													@"public.image"


@implementation ImagePickerController

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:NO];
	[weiBoEditor startUploadingOfPickedMediaIfNeed];
}

@end


@implementation ComposeViewController
@synthesize btnSend, btnCancel, btnInsert, sendingView, imgAttachment;
@synthesize messageTextField;
@synthesize pickedVideo;
@synthesize pickedPhoto;
@synthesize progressSheet;
@synthesize imgPicker;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(textChanged:) 
												 name:UITextViewTextDidChangeNotification 
											   object:messageTextField];
	imgPicker.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated {
	self.messageTextField.text = [self LoadSavedContent];
    [super viewWillAppear:animated];
}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
	[self ResetSavedContent];
    [super viewDidUnload];
}


- (void)dealloc {
	self.pickedPhoto = nil;
	self.pickedVideo = nil;
    [super dealloc];
}

- (IBAction)send:(id)sender {
	if(isNetworkAccessable())
	{
		[self postNewStatus];
		sendingView.hidden = NO;
	}else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
														message:NSLocalizedString(@"No Network Connection", @"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}

}

- (IBAction)cancel:(id)sender {
	messageTextField.text = @"";
	imgAttachment.image = nil;
	sendingView.hidden = YES;
	
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

- (IBAction)insert:(id)sender {
	
	BOOL imageAlreadyExists  = [self mediaIsPicked];
	BOOL photoCameraEnabled  = NO;
	BOOL photoLibraryEnabled = NO;
	BOOL movieCameraEnabled  = NO;
	BOOL movieLibraryEnabled = NO;
	
	NSArray *mediaTypes = nil;
	
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
	{
		photoLibraryEnabled = YES;
		if ([[UIImagePickerController class] respondsToSelector:@selector(availableMediaTypesForSourceType:)]) 
		{
			mediaTypes = [self availableMediaTypes:UIImagePickerControllerSourceTypePhotoLibrary];
			movieLibraryEnabled = [mediaTypes indexOfObject:K_UI_TYPE_MOVIE] != NSNotFound;
			photoLibraryEnabled = [mediaTypes indexOfObject:K_UI_TYPE_IMAGE] != NSNotFound;
		}
		
	}
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		photoCameraEnabled = YES;
		
		
		if ([[UIImagePickerController class] respondsToSelector:@selector(availableMediaTypesForSourceType:)]) 
		{
			mediaTypes = [self availableMediaTypes:UIImagePickerControllerSourceTypeCamera];
			movieCameraEnabled = [mediaTypes indexOfObject:K_UI_TYPE_MOVIE] != NSNotFound;
			photoCameraEnabled = [mediaTypes indexOfObject:K_UI_TYPE_IMAGE] != NSNotFound;
		}
	}
	
	NSString *buttons[5] = {0};
	int i = 0;
	
	if(photoCameraEnabled)
		buttons[i++] = NSLocalizedString(@"Take Photo", @"");
	//if(movieCameraEnabled)
	//	buttons[i++] = NSLocalizedString(@"Use video camera", @"");
	if(photoLibraryEnabled)
		buttons[i++] = NSLocalizedString(@"User Library", @"");;
	//	if(movieLibraryEnabled)
	//		buttons[i++] = NSLocalizedString(@"Use video library", @"");
	if(imageAlreadyExists)
		buttons[i++] = NSLocalizedString(@"Remove Image", @"");
	
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
															 delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"") destructiveButtonTitle:nil
													otherButtonTitles:buttons[0], buttons[1], buttons[2], buttons[3], buttons[4], nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
	actionSheet.tag = PHOTO_Q_SHEET_TAG;
	[actionSheet showInView:self.view];
	[actionSheet release];
	
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(actionSheet.tag == PHOTO_Q_SHEET_TAG)
	{
		if(buttonIndex == actionSheet.cancelButtonIndex)
			return;
		
		[self SaveCurrentContent];

		if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"Remove Image", @"")])
		{
			[self setImage:nil movie:nil];
			return;
		}
		if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"Take Photo", @"")])
		{
			imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
			if([imgPicker respondsToSelector:@selector(setMediaTypes:)])
				[imgPicker performSelector:@selector(setMediaTypes:) withObject:[NSArray arrayWithObject:K_UI_TYPE_IMAGE]];
			[self presentModalViewController:imgPicker animated:YES];
			return;
		}
/*		
		else if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"User Library", @"");])
		{
			imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
			if([imgPicker respondsToSelector:@selector(setMediaTypes:)])
				[imgPicker performSelector:@selector(setMediaTypes:) withObject:[NSArray arrayWithObject:K_UI_TYPE_MOVIE]];
			[self presentModalViewController:imgPicker animated:YES];
			return;
		}
 */
		else if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"User Library", @"")])
		{
			imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
			if([imgPicker respondsToSelector:@selector(setMediaTypes:)])
				[imgPicker performSelector:@selector(setMediaTypes:) withObject:[self availableMediaTypes:UIImagePickerControllerSourceTypePhotoLibrary]];
			[self presentModalViewController:imgPicker animated:YES];
			return;
		}
		
	}
}

- (void)focusInput {
	[messageTextField becomeFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated {
	[self focusInput];
	draft.text = messageTextField.text;
	btnSend.enabled = messageTextField.text.length > 0;
	btnInsert.enabled = messageTextField.text.length > 0;
}

- (void)textChanged:(NSNotification *)notification{
	int maxLength = 140;
	btnSend.enabled = messageTextField.text.length > 0;
	btnInsert.enabled = messageTextField.text.length > 0;
	if (messageTextField.text.length >= maxLength)
    {
        messageTextField.text = [messageTextField.text substringToIndex:maxLength];
    }
	draft.text = messageTextField.text;
}

- (void)newTweet {
	[draft release];
	draft = [[Draft alloc]initWithType:DraftTypeNewTweet];
	[self focusInput];
}

- (void)postNewStatus
{
	NSLog(@"Weibo info: %@",draft.text);
	WeiboClient *client = [[WeiboClient alloc] initWithTarget:self 
													   engine:[OAuthEngine currentOAuthEngine]
													   action:@selector(postStatusDidSucceed:obj:)];
	client.context = [draft retain];
	draft.draftStatus = DraftStatusSending;
	if (draft.attachmentImage) {
		[client upload:draft.attachmentData status:draft.text];
	}
	else {
		[client post:draft.text];
	}
}

- (void)postStatusDidSucceed:(WeiboClient*)sender obj:(NSObject*)obj;
{
	Draft *sentDraft = nil;
	if (sender.context && [sender.context isKindOfClass:[Draft class]]) {
		sentDraft = (Draft *)sender.context;
		[sentDraft autorelease];
	}
	
    if (sender.hasError) {
        [sender alert];	
		[self cancel:nil];
        return;
    }
    
    NSDictionary *dic = nil;
    if (obj && [obj isKindOfClass:[NSDictionary class]]) {
        dic = (NSDictionary*)obj;    
    }
	
    if (dic) {
        Status* sts = [Status statusWithJsonDictionary:dic];
		if (sts) {
			//delete draft!
			if (sentDraft) {
				
			}
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
															message:NSLocalizedString(@"Post Successfully!", @"")
														   delegate:nil 
												  cancelButtonTitle:@"OK"
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
    }
	[self cancel:nil];
}

- (void)setImageImage:(UIImage*)newImage
{
	//image.image = newImage;
	//[self setURLPlaceholder];
	//[self setNavigatorButtons];
}

- (void) setImage:(UIImage*)img movie:(NSURL*)url
{
	self.pickedPhoto = img;
	self.pickedVideo = url;
	UIImage* prevImage = nil;
	if(img)
		prevImage = img;
	else if(url)
		prevImage = [UIImage imageNamed:@"MovieIcon.tif"];
	[self setImageImage:prevImage];
	draft.attachmentImage = self.pickedPhoto;
	imgAttachment.image = self.pickedPhoto;	
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	//messageTextWillIgnoreNextViewAppearing = YES;
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
	[messageTextField becomeFirstResponder];
	//[self setNavigatorButtons];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishWithPickingPhoto:(UIImage *)img pickingMovie:(NSURL*)url
{
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
	//twitWasChangedManually = YES;
	//messageTextWillIgnoreNextViewAppearing = YES;
	
	BOOL startNewUpload = NO;
	
	if(pickedPhoto != img || pickedVideo != url)
	{
		startNewUpload = YES;
		[self setImage:img movie:url];
	}
	
	//[self setNavigatorButtons];
	/*
	if(startNewUpload)
	{
		if(self.connectionDelegate)
			[self.connectionDelegate cancel];
		self.connectionDelegate = nil;
		self.currentMediaYFrogURL = nil;
	}
	*/
	[messageTextField becomeFirstResponder];
	
	if(img)
	{
		//BOOL needToResize;
		//BOOL needToRotate;
		//isImageNeedToConvert(img, &needToResize, &needToRotate);
		//if(needToResize || needToRotate)
		{
			self.progressSheet = ShowActionSheet(NSLocalizedString(@"Processing image...", @""), self, nil, self.view);
			self.progressSheet.tag = PROCESSING_PHOTO_SHEET_TAG;
		}
	}
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	
	if([[info objectForKey:@"UIImagePickerControllerMediaType"] isEqualToString:K_UI_TYPE_IMAGE])
		[self imagePickerController:picker didFinishWithPickingPhoto:[info objectForKey:@"UIImagePickerControllerOriginalImage"] pickingMovie:nil];
	else if([[info objectForKey:@"UIImagePickerControllerMediaType"] isEqualToString:K_UI_TYPE_MOVIE])
		[self imagePickerController:picker didFinishWithPickingPhoto:nil pickingMovie:[info objectForKey:@"UIImagePickerControllerMediaURL"]];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo 
{
	[self imagePickerController:picker didFinishWithPickingPhoto:img pickingMovie:nil];
}


- (NSArray*)availableMediaTypes:(UIImagePickerControllerSourceType) pickerSourceType
{
	SEL selector = @selector(availableMediaTypesForSourceType:);
	NSMethodSignature *sig = [[UIImagePickerController class] methodSignatureForSelector:selector];
	NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
	[invocation setTarget:[UIImagePickerController class]];
	[invocation setSelector:selector];
	[invocation setArgument:&pickerSourceType atIndex:2];
	[invocation invoke];
	NSArray *mediaTypes = nil;
	[invocation getReturnValue:&mediaTypes];
	return mediaTypes;
}

- (BOOL)mediaIsPicked
{
	return pickedPhoto || pickedVideo;
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	
}

- (void)startUpload
{	
	if(self.pickedPhoto)
		self.pickedPhoto = imageScaledToSize(self.pickedPhoto, IMAGE_SCALING_SIZE);
		
}

- (void)startUploadingOfPickedMediaIfNeed
{
	if(self.pickedPhoto)
		[self startUpload];
	
	if(self.progressSheet && self.progressSheet.tag == PROCESSING_PHOTO_SHEET_TAG)
	{
		[self.progressSheet dismissWithClickedButtonIndex:-1 animated:YES];
		self.progressSheet = nil;
	}		
}

-(void)SaveCurrentContent{
	[[NSUserDefaults standardUserDefaults] setValue:self.messageTextField.text forKey:@"SavedWeiBoText"];
}

-(void)ResetSavedContent{
	[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"SavedWeiBoText"];
}

-(NSString *)LoadSavedContent{
	return [[NSUserDefaults standardUserDefaults] stringForKey:@"SavedWeiBoText"];
}

@end
